<script lang="ts" setup>
import Select from './ProductContainer/Select.vue'
import Product from './ProductContainer/Product.vue'
import type { SubCategoryList } from '@/typings/api'
import XLoadMore from '@/components/XLoadMore.vue'

defineProps<{
  subCategory: SubCategoryList[]
}>()

// 切换页面滑动与否
const emit = defineEmits<{
  (e: 'syncOverflowState', value: string): void
}>()

// 是否展示二级分类下拉框
let showSelect = $ref(false)

// 滑动样式
const ovewflowState = $computed(() => {
  return showSelect ? 'hidden' : 'visible'
})

// 点击二级分类
function switchSelect() {
  showSelect = !showSelect
  // 兼容H5的滚动
  // #ifdef H5
  document.body.style.overflow = ovewflowState
  // #endif
  // 选中后关闭二级分类下拉框，回复页面可滚动
  emit('syncOverflowState', ovewflowState)
}

const { end, products, sendRequest } = $(useCategory())

// 滑动加载展示设置
let loadMoreStatus = $ref<'more' | 'loading' | 'nomore'>('more')

// 设置加载更多的全局事件
uni.$on('categoryLoadMore', async () => {
  loadMoreStatus = 'loading'
  await sendRequest(true)
  loadMoreStatus = end ? 'nomore' : 'more'
})

</script>

<template>
  <view class="container">
    <Select :show="showSelect" :sub-category="subCategory.filter((item) => item.name)" @update:show="switchSelect" />
    <view class="tab">
      <view class="select_btn" @click="switchSelect">
        <text>筛选</text>
        <image src="@/static/images/icons/category/arrow_down.svg" :class="!showSelect && 'rotate'" />
      </view>
    </view>
    <view class="products">
      <Product v-for="item in products" :key="item.id" :product="item" />
    </view>
    <XLoadMore :status="loadMoreStatus" />
  </view>
</template>

<style lang="scss" scoped>
.container {
  background-color: white;
  border-top-left-radius: 30rpx;
  border-top-right-radius: 30rpx;
  padding: 30rpx 35rpx;
  position: relative;
  box-sizing: border-box;

  .tab {
    display: flex;
    position: relative;
    justify-content: space-around;

    .select_btn {
      position: relative;

      image {
        width: 14rpx;
        height: 8rpx;
        position: absolute;
        top: 45%;
        left: 120%;

        &.rotate {
          transform: rotate(180deg);
        }
      }
    }

    text {
      color: #4d555d;
      font-size: 30rpx;

      &.active {
        color: #f38e48;
      }
    }
  }

  .products {
    display: flex;
    flex-wrap: wrap;
    margin-top: 20rpx;
    justify-content: space-between;
  }
}
</style>
